package pattern.factory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author zhang peng yang ming
 * @create 2018-07-21 10:52
 */
public class Server {
    private ServerSocket server;
    public static void main(String[] args) {
        Server s = new Server();
        s.start();
    }

    /**
     * 初始化客户端
     * @param port
     * @throws IOException
     */
    public void init(int port) throws IOException {
        server = new ServerSocket(port);
    }

    /**
     * 服务器启动
     */
    public void start() {
        try {
            init(8888);
            while (true) {
                receive();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 接收客户端消息
     */
    public void receive() {
        try {
            Socket client = server.accept();

            InputStream is = client.getInputStream();
            Thread.sleep(500);
            byte[] cache = new byte[is.available()];
            is.read(cache);
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(new String(cache, "UTF-8"));
            System.out.println(stringBuffer.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 停止
     */
    public void stop() {
        try {
            server.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
